
var util = require('../../utils/util.js')
var utilMd5 = require('../../utils/md5.js');
var base64 = require('../../utils/Base64.js');

const Upyun = require('../../utils/upyun-wxapp-sdk');
var app = getApp();
var reload = true;
var buy_hasMore = true;
var buy_loadingMore = false;

var page = 1;
var tc = 0;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    util: util,
    tc: 0,

    buy_orders: [],
    hasBuyData:true,
    uid:0,
    token:'',
    openid:'',
    canEdit: 0,

    orderType: 2
  },

  orderType: 2,
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var tc = app.get_tc();
    var titlename = tc == 1 ? '訂單' : '订单';
    wx.setNavigationBarTitle({
      title: titlename,
    })
    
    var that = this;
    tc = app.get_tc();
    wx.getSystemInfo({
      success: function (res) {
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          isIphone_x: isIphone_x,
          screen_h: res.windowHeight,
          tc: tc
        });
      }
    });

    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color
      })
      that.resetNavColor();
    });

    page = 1;
    this.orderType = options.type ? options.type : 2;
    //当前登录用户信息
    app.LoginUserInfo(function (res) {
      //更新数据
      that.setData({
        uid: res.uid,
        token: res.token,
        openid: res.wxsmall_openid,
        orderType: that.orderType
      });
      that.getZongOrderList(that.orderType, 1, 20, true);
    });

    
  },

  loadMore: function (e) {
    if (buy_hasMore && !buy_loadingMore) {
        buy_loadingMore = true;
        page++;
      this.getZongOrderList(this.orderType, page, 20, false);
      } else {
        console.log("没有更多了");
      }
  },


  //获取订单 列表  type: 1 卖出  2:买入
  // * page: 
  // refresh 是否是刷新
  getZongOrderList: function (orderType, page, num, refresh) {
    wx.showLoading({
      title: '加载中',
      mask: 'true'
    })
    var that = this;
    var params = {
      "ac": "getzongorder",
      "publickey": util.publiccode,
      "type": orderType,
      "page": page,
      "num": num,
      "orgid": util.orgid
    };
    if(orderType == 1){//卖出
      params.ac = "admingetzongorder";
    }
    if (orderType == 2) {//买入
      params.uid = that.data.uid;
    }
    console.log("orders params:", params);
    util.api({
      data: params,
      success: function (responseData) {
        console.log(responseData);
        if (!responseData.data.msg) {
          console.log(responseData.data);
          //买入
          var result = responseData.data;
          if (!refresh && that.data.buy_orders.length > 0) {
            result = that.data.buy_orders.concat(responseData.data);
          }
          console.log('result:',result)
          that.setData({
            buy_orders: result
          });

        } else {
          //买入
          buy_hasMore = false;
          if (that.data.buy_orders.length <= 0) {
            that.setData({
              hasBuyData: false
            });
          }

        }
        //买入
        buy_loadingMore = false;

        wx.hideLoading();
      }
    });
  },

  //重新读取 登录用户信息
  reGetUserInfo: function (e) {
    var that = this;
    console.log("reGetUserInfo: ", e);
    if (e == 1) {
      // wx.reLaunch({ //用这个会报错fail can not invoke relaunch in background
      wx.redirectTo({
        url: '/pages/order-list/order-list'
      })
    } else {
      wx.redirectTo({
        url: '/pages/index/index'
      })
    }
  },

  recgoods:function() {
    console.log(123)
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  goAtherPage: function (e) {
    // var url = e.currentTarget.dataset.link;    
    // wx.navigateTo({ url: url })
  },
  goAtherPageRedirect: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.redirectTo({ url: url })
  },

  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if (path) {
      wx.redirectTo({ url: path })
    }
  },
  resetNavColor: function () {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },

  //支付订单推送
  paytuisong: function (e) {
    console.log(e);
    var that = this;
    var order = that.data.order;
    console.log("paytuisong");

    var g_info = '';
    for (var i = 0; i < order.fendan.length; i++) {
      var goodsItem = order.fendan[i];
      g_info = g_info + goodsItem.goods_name + '  ' + goodsItem.count + ' 瓶；' + '  ';
    }

    var tmpmd5 = utilMd5.hexMD5(that.data.uid + "paytuisong" + that.data.token);
    var data = {
      "privatekey": tmpmd5,
      "ac": "paytuisong",
      "uid": that.data.uid,
      // "cartinfo": JSON.stringify(cartinfoArr),
      "binduid": util.orgid,
      "total_fee": order.total_fee/100,
      "name": order.fendan[0].consignee,
      "phone": order.fendan[0].phone,
      "address": order.fendan[0].addr,
      'out_trade_no': order.out_trade_no,
      'booktime': order.booktime,
      "btime": that.toDate(order.ctime),
      'goods_list': g_info,
    };

    util.api({
      data: data,
      method: "POST",
      success: function (responseData) {
        console.log("paytuisong===", responseData);
      }
    });
  }, 
  //时间戳转换时间  
  toDate: function (number) {
    var n = number * 1000;
    var date = new Date(n);
    var Y = date.getFullYear() + '.';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '.';
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var H = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
    var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    console.log(Y + M + D + "  " + H + ':' + m)
    return (Y + M + D + "  " + H + ':' + m)

  }

})